package com.waimai.mobile.misc;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lin on 2015/6/19.
 */

public class ImageLoader{

    private static Map<String ,SoftReference<Bitmap>> cacheMap = new HashMap<String ,SoftReference<Bitmap>>();


    public static void load(final String imageUrl, ImageView image){

        SoftReference<Bitmap> reference = cacheMap.get(imageUrl);
        if (reference != null){
            Bitmap bitmap = reference.get();
            if(bitmap != null) {
                image.setImageBitmap(reference.get());
                return ;
            }
        }
        new LoadTask(imageUrl, image).execute();
    }

    private static class LoadTask extends AsyncTask<Void, Void, Bitmap>{

        public String imageUrl;
        public ImageView image;

        public LoadTask(String imageUrl, ImageView image){
            this.image = image;
            this.imageUrl = imageUrl;
        }

        @Override
        protected Bitmap doInBackground(Void... params) {
            InputStream is = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(this.imageUrl);
                is =url.openStream();
                bitmap = BitmapFactory.decodeStream(is);

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if(is != null)
                        is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if(bitmap != null){
                image.setImageBitmap(bitmap);
                SoftReference<Bitmap> reference = new SoftReference<Bitmap>(bitmap);
                cacheMap.put(imageUrl, reference);
            }else{
                System.out.println("加载图片失败-----");
            }
        }
    }


}
